package org.windblog.core;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import org.windblog.core.entity.Archive;
import org.windblog.core.entity.Post;

public class ArchiveService {

	/**
	 * 获取archives.可以有如下几种: 
	 * monthly : 按月的Archives. 
	 * yearly  : 按年的Archives.
	 * daily   : 按日的Archives. 
	 * weekly  : 按周的Archives.
	 * 
	 * @param type may be "monthly","yearly","daily","weekly".
	 * @return Archives
	 * @throws Exception 
	 */
	public static List<Archive> getArchives(String type) {
		List<Archive> archives = new LinkedList<Archive>();

		Archive acv = null;

		List<Post> posts = PostService.getPosts("");//获取所有日志

		Calendar calendar = GregorianCalendar.getInstance();
		calendar.set(Calendar.YEAR, 2210); // 设置一个很远的未来的时间

		for (Post p : posts) {
			Date date = p.getDate();
			if (!date.before(calendar.getTime())) { 
				acv.addCount();
			} else {
				if (type.equals("monthly")) {
					calendar.setTime(date);
					calendar.set(Calendar.DAY_OF_MONTH, 1);
					calendar.set(Calendar.HOUR_OF_DAY, 0);
					calendar.set(Calendar.MINUTE, 0);
					calendar.set(Calendar.SECOND, 0);
					acv = new Archive();
					acv.setName(calendar.getDisplayName(Calendar.MONTH,
							Calendar.LONG, Locale.CHINA)+" "+calendar.get(Calendar.YEAR));
					acv.setType("m");
					acv.setValue(calendar.get(Calendar.YEAR) + ""
							+ (calendar.get(Calendar.MONTH)+1));
				}else if(type.equals("yearly")){
					calendar.set(Calendar.MONTH, 1);
					calendar.setTime(date);
					calendar.set(Calendar.DAY_OF_MONTH, 1);
					calendar.set(Calendar.HOUR_OF_DAY, 0);
					calendar.set(Calendar.MINUTE, 0);
					calendar.set(Calendar.SECOND, 0);
					acv = new Archive();
					acv.setName(calendar.get(Calendar.YEAR)+"年");
					acv.setType("y");
					acv.setValue(calendar.get(Calendar.YEAR)+"");
				}else{
					throw new Error("The argument "+type+" is not correct.");
				}
				
				acv.addCount();
				archives.add(acv);
			}
		}

		return archives;
	}

}
